package cn.benben.dubbo.filter;

import cn.benben.core.constant.SecurityConstants;
import cn.benben.core.context.SecurityContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * @author xn
 * 数据透传
 */


@Slf4j
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, order = Integer.MAX_VALUE)
public class RpcFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        log.info("RpcFilter------");

        RpcServiceContext serviceContext = RpcContext.getServiceContext();
        if (serviceContext.getUrl() == null){
            return invoker.invoke(invocation);
        }
        if (RpcContext.getServiceContext().isConsumerSide()) {
            log.info("RpcConsumeFilter------");
            invocation.setAttachment(SecurityConstants.USER_ID, SecurityContextHolder.getUserId());
            invocation.setAttachment(SecurityConstants.USER_NAME,SecurityContextHolder.getUserName());
        }else {
            log.info("RpcProviderFilter------");
            SecurityContextHolder.setUserId(invocation.getAttachment(SecurityConstants.USER_ID));
            SecurityContextHolder.setUserName(invocation.getAttachment(SecurityConstants.USER_NAME));
        }
        return invoker.invoke(invocation);
    }
}
